/**
 * 
 */
package org.ycsoft.metroid;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author lookouster
 *
 */
public class RepoSearchResults extends Activity{
	
	
	public static boolean dlgHide;
	TextView title, keys;
	ListView resultsList;
	Button cancel;
	String city, mean;
	public InputStream repoStream;
	public static final String TAG = "Metroid";
	public String repoURI;
	List<URL> resultURLsList;
	List<String>resultCitiesList;
	List<String> resultsDisplay;
	RepoDownload downloadDlg;
	Handler handler;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr;
	List<RepoMatchedItem> results;
	
	
	@Override
	public void onCreate(Bundle icicle)
	{         
		super.onCreate(icicle);
		setContentView(R.layout.results);
		title=(TextView)findViewById(R.id.title_results);
		keys=(TextView)findViewById(R.id.key_results);
		resultsList=(ListView)findViewById(R.id.list_results);
		cancel=(Button)findViewById(R.id.close_results);
		cancel.setOnClickListener(btnCancelListener);
		loadEverything();

}
	public void loadEverything()
	{
		title.setText(R.string.title_search);
		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			city = extras.getString(Commons.KEY_CITY);
			mean = extras.getString(Commons.KEY_MEAN);
		}
		else
			finish();
		keys.setText(Commons.KEY_CITY+Commons.EQ+city+" "+ Commons.KEY_MEAN+Commons.EQ+mean);
		repoURI=Commons.URLRepo+Commons.KEY_CITY+Commons.EQ+city+Commons.KEY_COM+
								Commons.KEY_MEAN+Commons.EQ+mean;
		//repoURI=Commons.URLRepo;
		Log.e(TAG,repoURI);
		RepoXMLHandler repoHandler = new RepoXMLHandler();
		          /* Create a URL we want to load some xml-data from. */ 
		            URL url;
					try {
						url = new URL(repoURI);
						try {
							url.openConnection();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							Log.e(TAG, "URL PB");
							//e1.printStackTrace();
						}
			             /* Get a SAXParser from the SAXPArserFactory. */ 
			            spf = SAXParserFactory.newInstance(); 
			              try {
							sp = spf.newSAXParser();
				              /* Get the XMLReader of the SAXParser we created. */ 
				              try {
								xr = sp.getXMLReader();
								/*Set a content Hanlder for our xml file before parsing'em*/
								xr.setContentHandler(repoHandler); 
								 /* Parse the xml-data from our URL. */ 
					             try {
									xr.parse(new InputSource(url.openStream()));
								} catch (IOException e) {
									// TODO Auto-generated catch block
									Log.e(TAG,"parse function pb "+e.getMessage());
								} 
					              /* Parsing has finished. */
						 
						          
						          /* Our RepoHandler now provides the parsed data to us. */ 
						             results = repoHandler.getParsedData(); 
						             //RepoRequestedItem req=repoHandler.getRequest();
						             //Log.e(TAG,xr.toString());
						             //Log.e(TAG, req.toString());

							} catch (SAXException e) {
								// TODO Auto-generated catch block
								Log.e(TAG, "XMLReader still messin up!!"+e.getMessage());
							}       
				            
						} catch (SAXParseException e) {
							// TODO Auto-generated catch block
							Log.e(TAG,"new SAXParser "+e.getMessage());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							//e.printStackTrace();
							Log.e(TAG, e.getMessage()+"ParserConfig");
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							//e.printStackTrace();
							Log.e(TAG, e.getMessage()+"SAXY");
						} 


					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						Log.e(TAG,"pb encountered with the url "+e.getMessage());
					} 

						                
			
					
		buildResultList();  		
	}
	
		public void buildResultList()
		{
			resultsDisplay=new ArrayList<String>();
			resultURLsList=new ArrayList<URL>();
			resultCitiesList=new ArrayList<String>();
			Log.e(TAG,results.toString());
			//Build what we're going to display
			if(results.size()>0)
			for(RepoMatchedItem item:results)
			{
				resultURLsList.add(item.getUrl());
				resultsDisplay.add(item.toString());
				resultCitiesList.add(item.getCity());
			}
			else
			{
				resultsDisplay.add("pouf");
				resultsDisplay.add("poufiasse");
			}
			ArrayAdapter<String> resultsAdapter=new ArrayAdapter<String>
			(this, R.layout.listbb,resultsDisplay);
			resultsList.setAdapter(resultsAdapter);
			resultsList.setOnItemClickListener(downloadMap);
		}
		
		
		
		private OnItemClickListener downloadMap=new OnItemClickListener()
		{
			public void onItemClick(AdapterView arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				launchDownloadDlg(position);
			}
		};
		/**
		 * Launch map download
		 * @param position position of the clicked item in the result list
		 */
		
		public void launchDownloadDlg(int position)
		{
			downloadDlg=new RepoDownload(this);
			downloadDlg.setMapLink(resultURLsList.get(position));
			downloadDlg.setCityMap(resultCitiesList.get(position));
			downloadDlg.show();	
		}
		
		private OnClickListener btnCancelListener=new OnClickListener()
		{

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
			
		};
				
		
}
